#include <iostream>
#include <vector>
#include <string>

using namespace std;

// TODO

// 有问题
int findLongestSubstring(const vector<int> &site)
{
    int longest = 0, len = 0;
    for (size_t i = 0; i < site.size(); i++)
    {
        if (site[i] == 0)
        {
            len++;
        }
        else
        {
            if (len > longest)
            {
                longest = len;
                len = 0;
            }
        }
    }
    return longest > len ? longest : len;
}

int longestValidParentheses(string s)
{
    vector<int> site(s.size(), 1);
    vector<char> stk;
    for (size_t i = 0; i < s.size(); i++)
    {
        if (s[i] == '(')
        {
            stk.push_back(s[i]);
        }
        else
        {
            if (!stk.empty() && stk.back() == '(')
            {
                stk.pop_back();
                site[i] = 0;
                size_t t = i - 1;
                while (t >= 0 && site[t] != 1)
                    t--;
                site[t] = 0;
            }
            else
            {
                stk.push_back(')');
            }
        }
    }
    return findLongestSubstring(site);
}

int main()
{
    string s = ")(()(()(((())(((((()()))((((()()(()()())())())()))()()()())(())()()(((()))))()((()))(((())()((()()())((())))(())))())((()())()()((()((())))))((()(((((()((()))(()()(())))((()))()))())";
    cout << longestValidParentheses(s) << endl;
    return 0;
}
